package com.wechat.config;


import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;


/**
 *  统一事物管理
 */
@Aspect
@Component
public class TransactionAdviceConfig {
    
    private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.wechat.service..*.*(..))";
    
    @Autowired
    private PlatformTransactionManager transactionManager;
    
    @Bean
    public TransactionInterceptor txAdvice() {
        TransactionInterceptor tsi = new TransactionInterceptor();
        Properties properties = new Properties();
//        properties.setProperty("get*", "PROPAGATION_SUPPORTS");
//        properties.setProperty("select*", "PROPAGATION_SUPPORTS");
//        properties.setProperty("load*", "PROPAGATION_SUPPORTS");
//        properties.setProperty("query*", "PROPAGATION_SUPPORTS");
//        properties.setProperty("list*", "PROPAGATION_SUPPORTS");
//        properties.setProperty("add*", "PROPAGATION_REQUIRED");
//        properties.setProperty("insert*", "PROPAGATION_REQUIRED");
//        properties.setProperty("save*", "PROPAGATION_REQUIRED");
//        properties.setProperty("update*", "PROPAGATION_REQUIRED");
//        properties.setProperty("modify*", "PROPAGATION_REQUIRED");
//        properties.setProperty("do*", "PROPAGATION_REQUIRED");
//        properties.setProperty("del*", "PROPAGATION_REQUIRED");
//        properties.setProperty("remove*", "PROPAGATION_REQUIRED");
//        properties.setProperty("process*", "PROPAGATION_REQUIRED");
//        properties.setProperty("create*", "PROPAGATION_REQUIRED");
//        properties.setProperty("valid*", "PROPAGATION_REQUIRED");
//        properties.setProperty("do*", "PROPAGATION_REQUIRED");
//        properties.setProperty("write*", "PROPAGATION_REQUIRED");
//        properties.setProperty("cancel*", "PROPAGATION_REQUIRED");
        properties.setProperty("*", "PROPAGATION_REQUIRED,-Throwable");
        tsi.setTransactionAttributes(properties);
        tsi.setTransactionManager(transactionManager);
        return tsi;
    }
    
    @Bean
    public Advisor txAdviceAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }
    
    
}